<?php
Class Helper {

    function __construct($array = null) {
        if (!empty($array)) {
            foreach ($array as $key => $value) {
                $this->$key = $value;
            }
        }
    }
    
    function cut_string($str,$num){
        if(strlen($str) > $num){
            return substr($str,0,$num).'...';
        }
        else{
            return $str;
        }
    }
    
    function print_r($item){
        echo "<pre>";
        print_r($item);
        echo "</pre>";
    }
    
    function print_time_option($selected = 0){
        for($i=0;$i<24;$i++){
            if($i == $selected){
                echo "<option value=\"{$i}\" selected=\"selected\">{$i}.00น.</option>";
            }
            else{
                echo "<option value=\"{$i}\">{$i}.00น.</option>";
            }            
        }
    }
    
    function month_thai($key){
        $thai_month_arr = array(
            "0" => "",
            "1" => "มกราคม",
            "2" => "กุมภาพันธ์",
            "3" => "มีนาคม",
            "4" => "เมษายน",
            "5" => "พฤษภาคม",
            "6" => "มิถุนายน",
            "7" => "กรกฎาคม",
            "8" => "สิงหาคม",
            "9" => "กันยายน",
            "10" => "ตุลาคม",
            "11" => "พฤศจิกายน",
            "12" => "ธันวาคม"
        );
        return $thai_month_arr[$key];
    }

	function slashOperationArray($arr){
		foreach($arr as $key => $value){
			$type = gettype($value);
			if($type == 'array' || $type == 'object'){
				continue;
			}
			else{
				$arr[$key] = $this->slashOperation($value);
			}
		}
		return $arr;
	}
    //เพิ่ม slash สำหรับสัญลักษณ์ทางคณิตศาสตร์
    function slashOperation($str) {
        return addcslashes($str,'+-*/');
    }
    //เอา slash ออกสำหรับสํญลักษณ์ทางคณิตศาสตร์
    function unslashOperation($str){
        return str_replace(array('\+','\-','\*','\/'),array('+','-','*','/'),$str);
    }
    
    function get_uri() {
        $base = preg_replace('#' . getenv('DOCUMENT_ROOT') . '#', '', str_replace(array('\\', $page_index), array('/', ''), __FILE__));
        $tailer = preg_replace('#' . $base . '#', '', getenv('REQUEST_URI'), 1);
        $parse_url = parse_url(TAILER);
        $uri = explode("/", $parse_url['path']);
        parse_str($parse_url['query']);
        return $uri;
    }

    function load_cookie() {
        foreach ($_COOKIE as $key => $value) {
            $this->cookie->{$key} = $value;
        }
    }

    function redirect($href) {
        echo "<script>";
        echo "location.replace('{$href}');";
        echo "</script>";
    }

    function alert($text) {
        echo "<script>";
        echo "alert('{$text}');";
        echo "</script>";
    }

    // dely click 
    function aClose($a, $b) {
        echo <<<HTML
         <script>
          setTimeout(function (){parent.$('{$a}').click();},{$b});
          </script>
HTML;
    }

    // reload parent.windows.location
    function aCloseRe($a) {
        echo <<<HTML
         <script>
         setTimeout(function (){parent.window.location.reload();},{$a});
         </script>
HTML;
    }

    // redir location replace
    function redir($a, $b) {
        echo <<<HTML
         <script>
          setTimeout("location.replace('{$a}')",{$b});
         </script>
HTML;
    }

    // load gallery refrash
    function regallery() {
        echo <<<HTML
        <script>
        var $ = parent.$;
        $('#tabs-page .tabs-detail li[rel=gallery]').load('/'+parent.shop_domain+'/link_show_gallery');
        </script>
HTML;
    }

    // load video refrash
    function revideo() {
        echo <<<HTML
        <script>
        var $ = parent.$;
        $('#tabs-page .tabs-detail li[rel=video]').load('/'+parent.shop_domain+'/frm_video/');
        </script>
HTML;
    }

    // load about refrash
    function reabout() {
        echo <<<HTML
        <script>
        var $ = parent.$;
        $('#tabs-page .tabs-detail li[rel=about]').load('/'+parent.shop_domain+'/about');
        </script>
HTML;
    }

    function queryString_toArray($url) {
        $url = parse_url($url);
        $query_str = explode('&', $url['query']);
        $x = array();
        foreach ($query_str as $key => $value) {
            $buffer = explode('=', $value);
            $x[$buffer[0]] = $buffer[1];
        }
        return $x;
    }

    // get youtube id
    function youtube_id($url) {
        $x = $this->queryString_toArray($url);
        return $x['v'];
    }

    // get browser
    function getbrowser() {
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $bname = 'Unknown';
        $platform = 'Unknown';
        $version = "";

        //First get the platform?
        if (preg_match('/linux/i', $u_agent)) {
            $platform = 'linux';
        } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
            $platform = 'mac';
        } elseif (preg_match('/windows|win32/i', $u_agent)) {
            $platform = 'windows';
        }

        // Next get the name of the useragent yes seperately and for good reason
        if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) {
            $bname = 'Internet Explorer';
            $ub = "MSIE";
        } elseif (preg_match('/Firefox/i', $u_agent)) {
            $bname = 'Mozilla Firefox';
            $ub = "Firefox";
        } elseif (preg_match('/Chrome/i', $u_agent)) {
            $bname = 'Google Chrome';
            $ub = "Chrome";
        } elseif (preg_match('/Safari/i', $u_agent)) {
            $bname = 'Apple Safari';
            $ub = "Safari";
        } elseif (preg_match('/Opera/i', $u_agent)) {
            $bname = 'Opera';
            $ub = "Opera";
        } elseif (preg_match('/Netscape/i', $u_agent)) {
            $bname = 'Netscape';
            $ub = "Netscape";
        }

        // finally get the correct version number
        $known = array('Version', $ub, 'other');
        $pattern = '#(?<browser>' . join('|', $known) .
                ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
        if (!preg_match_all($pattern, $u_agent, $matches)) {
            // we have no matching number just continue
        }

        // see how many we have
        $i = count($matches['browser']);
        if ($i != 1) {
            //we will have two since we are not using 'other' argument yet
            //see if version is before or after the name
            if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) {
                $version = $matches['version'][0];
            } else {
                $version = $matches['version'][1];
            }
        } else {
            $version = $matches['version'][0];
        }

        // check if we have a number
        if ($version == null || $version == "") {
            $version = "?";
        }

//        return array(
//            'userAgent' => $u_agent,
//            'name' => $bname,
//            'version' => $version,
//            'platform' => $platform,
//            'pattern' => $pattern
//        );
        return $bname;
    }

    // function get ip
    function getRealIpAddr() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {   //to check ip is pass from proxy
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
	
    // get os
    function getOs() {
		include('Application/phpsniff/phpSniff.class.php');
        $phpsniff = new phpSniff;
        $phpsniff->init();

        $OSList = array
            (
            'Windows 3.11' => 'Win16',
            'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)',
            'Windows 98' => '(Windows 98)|(Win98)',
            'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
            'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
            'Windows Server 2003' => '(Windows NT 5.2)',
            'Windows Vista' => '(Windows NT 6.0)',
            'Windows 7' => '(Windows NT 7.0) | (Windows nt6.1)',
            'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
            'Windows NT 6.1' => 'Windows NT 6.1',
            'Windows ME' => 'Windows ME',
            'Open BSD' => 'OpenBSD',
            'Sun OS' => 'SunOS',
            'Linux' => '(Linux)|(X11)',
            'Mac OS' => '(Mac_PowerPC)|(Macintosh)|(osx)',
            'QNX' => 'QNX',
            'BeOS' => 'BeOS',
            'OS/2' => 'OS/2',
            'Search Bot' => '(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)'
        );
        $os = $phpsniff->_browser_info['os'];
        foreach ($OSList as $CurrOS => $Match) {
            if (strrpos($Match, $os)) {
                break;
            }
        }
        return $CurrOS;
        
    }
    
    function string_and_youtube($text){
        $text = ' '.$text.' ';
        $start = stripos($text,'http://www.youtube.com');
        if(!$start){
            $start = stripos($text,'www.youtube.com');
            if(!$start){
                $start = stripos($text,'youtube.com');
            }
        }
        if($start){
            $end_sp = stripos($text,' ',$start);
            $end_en = stripos($text,"\n",$start);
            if(!$end_en && !$end_sp){
                $end = strlen($text);
            }
            else if(!$end_en){
                $end = $end_sp;
            }
            else if(!$end_sp){
                $end = $end_en;
            }
            else if($end_sp > $end_en){
                $end = $end_en;
            }
            else if($end_sp < $end_en){
                $end = $end_sp;
            }
            $a = substr($text,0,$start);
            $b = substr($text,$end);

            $x = $this->queryString_toArray(substr($text,$start,$end-$start));
            $y_id = $x['v'];
            
            $c = <<<HTML
            <iframe width="420" height="315" src="http://www.youtube.com/embed/{$y_id}" frameborder="0" allowfullscreen></iframe>
HTML;
            return trim($a.$c.$b);
        }
        else{
            return trim($text);
        }
    }
}
